//------------------------------------------------------------------------------
#include <QtGui>
#include <QMessageBox>
#include <QDate>
#include <QDesktopServices>
#include <QProcess>
#include <QSqlRecord>
#include "CFindFrm.h"
#include "CTextEditDelegate.h"
#include "CComboResultFrm.h"
#include "CPrintFrm.h"
#include "CSelectArticleFrm.h"
#include "CDevisFrm.h"
#include "version.h"
#include "CMySQL.h"
#include "CHelp.h"
//------------------------------------------------------------------------------
CDevisFrm::CDevisFrm(QString name, QString lastCode, QWidget *parent) : CMyMainWindow(name, parent)
{
	setActionCur(CGlobal::acConstruct);
	
	setupUi(this);
	
	setStatusBar(NULL);
	
	actLock->setChecked(true);
	
	masterTable="teteDevis";
	primaryKey="code";
	curCode="0";
	status->addItem("CUR");
	status->addItem("ABO");
	status->addItem("NAB");
	
	tabWidget->removeTab(0);
	createGrille();
	
	commentaires=new CTextWidget(this);
	commentaires->setChamp("commentaires");
	commentaires->setTable("teteDevis");
	connect(commentaires, SIGNAL(textChanged()), this, SLOT(onChange()));
	connect(commentaires, SIGNAL(invokeHelp(CChamp*)), this, SLOT(onInvokeHelp(CChamp*)));
	tabWidget->addTab(commentaires, QIcon(), tr("Commentaires"));
	
	privateCommentaires=new CTextWidget(this);
	privateCommentaires->setChamp("privateCommentaires");
	privateCommentaires->setTable("teteDevis");
	connect(privateCommentaires, SIGNAL(textChanged()), this, SLOT(onChange()));
	connect(privateCommentaires, SIGNAL(invokeHelp(CChamp*)), this, SLOT(onInvokeHelp(CChamp*)));
	tabWidget->addTab(privateCommentaires, QIcon(), tr("Commentaires privés"));
	
	loadSchema();
	
	loadPrintPopupMenu(toolBar);
	
	if(CMySQL::getInstance()->getNbEnregistrement(masterTable) == 0)
	{
		setActionCur(CGlobal::acTableVide);
	}else
	{
		if(!chargeDonnees(lastCode, CGlobal::seNone)) chargeDonnees("", CGlobal::sePremier);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::setNumero(int numero)
{
	chargeDonnees(QString::number(numero), CGlobal::seNone);	
}
//------------------------------------------------------------------------------
void CDevisFrm::setActionCur(CGlobal::EAction action)
{
	actionCur=action;
	
	switch(actionCur)
	{
		case CGlobal::acNone:
			actPremiereFiche->setEnabled(true);
			actFichePrecedente->setEnabled(true);
			actFicheSuivante->setEnabled(true);
			actDerniereFiche->setEnabled(true);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(true);
			actCopierDevis->setEnabled(true);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(true);
			enableBtnPrint(true);
			
			enableChamps(true);
			lignesWidget->setEnabled(true);
			status->setEnabled(true);
			avertModifClientShown=false;
			break;
		case CGlobal::acTableVide:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(false);
			actCopierDevis->setEnabled(false);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(false);
			enableBtnPrint(false);
			
			clearChamps();
			enableChamps(false);
			code->setValue("");
			creation->setValue("");
			
			lignesWidget->setEnabled(false);
			status->setEnabled(false);
			lignesWidget->setRowCount(0);
			break;
		case CGlobal::acAjout:
		case CGlobal::acAjoutFromOther:
			clearChamps();
			initChamps();
			enableChamps(true);
	
			code->setText("");
			codeClient->setFocus();
			lignesWidget->setRowCount(0);
			status->setCurrentIndex(0);
		case CGlobal::acModif:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			actCopierDevis->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
			enableBtnPrint(false);
			
			lignesWidget->setEnabled(false);
			status->setEnabled(true);
			break;
		case CGlobal::acAfficheLigne:
		default:
			break;
	}
}
//------------------------------------------------------------------------------
CGlobal::EAction CDevisFrm::getActionCur(void)
{
	return actionCur;
}
//------------------------------------------------------------------------------
void CDevisFrm::closeEvent(QCloseEvent * event)
{
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acTableVide)
	{
		QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
							tr("Veuillez annuler ou valider avant de sortir"), QMessageBox::Ok);
		msgBox.exec();	
		
		event->ignore();
	}else
	{
		emit quit(objectName(), curCode);
		event->accept();
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::createGrille(void)
{
	CTextEditDelegate *delegate=new CTextEditDelegate();
	QList<CColumnModel *> *columnModel=new QList<CColumnModel *>();
	
	columnModel->append(new CColumnModelInt(cndLigne, "numeroLigne", tr("Ligne"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cndArticle, "article", tr("Article"), Qt::AlignLeft, 
			new QIcon(":coMexpert/images/camera.png"), Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelString(cndDescArticle, "descriptionArticle", tr("Description")));
	columnModel->append(new CColumnModelDouble(cndQuantite, "quantite", tr("Qté.")));
	columnModel->append(new CColumnModelString(cndUnite, "unite", tr("Unité"), Qt::AlignLeft, 
			new QIcon(":coMexpert/images/attach.png"), Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cndPrix, "prixUnitaireHT", tr("Prix")));
	columnModel->append(new CColumnModelDouble(cndTotal, "", tr("Total"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	columnModel->append(new CColumnModelDouble(cndTva, "taux", tr("Taux de TVA"), Qt::AlignRight, NULL, Qt::ItemIsEnabled));
	
	lignesWidget=new CGrilleWidget(columnModel, this, true, true);
	connect(lignesWidget, SIGNAL(ajoute(bool&)), this, SLOT(ajouteLigne(bool&)));
	connect(lignesWidget, SIGNAL(supprime(int, bool&)), this, SLOT(supprimeLigne(int, bool&)));
	connect(lignesWidget, SIGNAL(monte(int)), this, SLOT(monteLigne(int)));
	connect(lignesWidget, SIGNAL(descend(int)), this, SLOT(descendLigne(int)));
	connect(lignesWidget, SIGNAL(cellChanged(int, int)), this, SLOT(modifiLigne(int, int)));
	connect(lignesWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(ligneDoubleClicked(int, int)));
	
	tabWidget->addTab(lignesWidget, tr("Lignes"));
	
	lignesWidget->setColumnWidth(cndDescArticle, 250);
	
	lignesWidget->setItemDelegateForColumn(cndDescArticle, delegate);
}
//------------------------------------------------------------------------------
void CDevisFrm::loadInfoClient(QString client)
{
	QSqlQuery *query;
	QString requete;
	
	requete="SELECT client.nom AS nomClient, adresse1, adresse2, adresse3, codePostal, ville, pays, ";
	requete+="modeReglement, conditionReglement, contactClient.nom AS nomContact ";
	requete+="FROM client LEFT JOIN contactClient on client=code ";
	requete+="WHERE code = \""+client+"\" ORDER BY defaut DESC, numero LIMIT 1";
		
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		if(query->next())
		{
			QSqlRecord rec=query->record();
			
			nomClient->setValue(rec.value("nomClient"));
			nomClient2->setValue(rec.value("nomClient"));
			adresse1->setValue(rec.value("adresse1"));
			adresse2->setValue(rec.value("adresse2"));
			adresse3->setValue(rec.value("adresse3"));
			codePostal->setValue(rec.value("codePostal"));
			ville->setValue(rec.value("ville"));
			pays->setValue(rec.value("pays"));
			modeReglement->setValue(rec.value("modeReglement"));
			conditionReglement->setValue(rec.value("conditionReglement"));
			attn->setValue(rec.value("nomContact"));
		}else
		{
			nomClient->setValue("");
			adresse1->setValue("");
			adresse2->setValue("");
			adresse3->setValue("");
			codePostal->setValue("");
			ville->setValue("");
			pays->setValue("");
			modeReglement->setValue("");
			conditionReglement->setValue("");
			attn->setValue("");
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CDevisFrm::loadInfoProspect(QString prospect)
{
	QSqlQuery *query;
	QString requete;
	
	requete="SELECT prospect.nom AS nomProspect, adresse1, adresse2, adresse3, ";
	requete+="codePostal, ville, pays, contactProspect.nom AS nomContact ";
	requete+="FROM prospect LEFT JOIN contactProspect ON prospect=code ";
	requete+="WHERE code = \""+prospect+"\" ORDER BY defaut DESC, numero LIMIT 1";
		
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		if(query->next())
		{
			QSqlRecord rec=query->record();
			
			nomClient->setValue(rec.value("nomProspect"));
			adresse1->setValue(rec.value("adresse1"));
			adresse2->setValue(rec.value("adresse2"));
			adresse3->setValue(rec.value("adresse3"));
			codePostal->setValue(rec.value("codePostal"));
			ville->setValue(rec.value("ville"));
			pays->setValue(rec.value("pays"));
			attn->setValue(rec.value("nomContact"));
		}else
		{
			nomClient->setValue("");
			adresse1->setValue("");
			adresse2->setValue("");
			adresse3->setValue("");
			codePostal->setValue("");
			ville->setValue("");
			pays->setValue("");
			attn->setValue("");
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CDevisFrm::loadInfoAdresse(int numeroAdresse)
{
	QSqlQuery *query;
	QString requete;
		
	requete="SELECT nom, adresse1, adresse2, adresse3, codePostal, ville, pays ";
	requete+="FROM adressesClient WHERE client = \""+codeClient->getValue()+"\" AND numero = "+QString::number(numeroAdresse);
		
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		if(query->next())
		{
			QSqlRecord rec=query->record();
			
			nomClient->setValue(rec.value("nom"));
			adresse1->setValue(rec.value("adresse1"));
			adresse2->setValue(rec.value("adresse2"));
			adresse3->setValue(rec.value("adresse3"));
			codePostal->setValue(rec.value("codePostal"));
			ville->setValue(rec.value("ville"));
			pays->setValue(rec.value("pays"));
			
		}else
		{
			nomClient->setValue("");
			adresse1->setValue("");
			adresse2->setValue("");
			adresse3->setValue("");
			codePostal->setValue("");
			ville->setValue("");
			pays->setValue("");
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CDevisFrm::loadGrille(void)
{
	CGlobal::EAction oldAction=getActionCur();
	QString requete;
	QSqlQuery *query;
	
	setActionCur(CGlobal::acAfficheLigne);
	
	requete="SELECT ld.numeroLigne, ld.article, ld.descriptionArticle, ld.quantite, ld.unite, ";
	requete+="ld.prixUnitaireHT, ld.quantite*ld.prixUnitaireHT, tauxTva*100 AS taux, 0 ";
	requete+="FROM ligneDevis AS ld ";
	requete+="WHERE devis="+curCode+" ";
	requete+="ORDER BY numeroLigne";
	
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		lignesWidget->loadGrille(query);
	}
	delete query;
	
	calculMontant();
	
	setActionCur(oldAction);
}
//------------------------------------------------------------------------------
void CDevisFrm::calculMontant(int ignoreRow)
{
	int y;
	double mnt=0;
	double mntTTc=0;
	
	for(y=0;y<lignesWidget->rowCount();y++)
	{
		if(y != ignoreRow)
		{
			double mntL=lignesWidget->item(y, cndTotal)->text().toDouble();
			mnt+=mntL;
			mntTTc+=mntL*(1+lignesWidget->item(y, cndTva)->text().toDouble()/100);
		}
	}
	
	montant->setText(QString("%1").arg(mnt, 0, 'f', 2));
	TTC->setText(QString("%1").arg(mntTTc, 0, 'f', 2));
}
//------------------------------------------------------------------------------
void CDevisFrm::calculTotalLigne(int row)
{
	double total=lignesWidget->item(row, cndQuantite)->text().toDouble()*lignesWidget->item(row, cndPrix)->text().toDouble();
	
	lignesWidget->item(row, cndTotal)->setText(QString("%1").arg(total, 0, 'f', 2));
}
//------------------------------------------------------------------------------
void CDevisFrm::loadEnteteFromOther(void)
{
	QString requete;
	QSqlQuery *query;
	
	requete="SELECT * FROM teteDevis WHERE code = "+curCode;
	
	if(CMySQL::getInstance()->execQuery(requete, &query))
	{
		if(query->next())
		{
			QSqlRecord rec=query->record();
			
			codeClient->setValue(rec.value("codeClient"));
			nomClient->setValue(rec.value("nomClient"));
			adresse1->setValue(rec.value("adresse1"));
			adresse2->setValue(rec.value("adresse2"));
			adresse3->setValue(rec.value("adresse3"));
			codePostal->setValue(rec.value("codePostal"));
			ville->setValue(rec.value("ville"));
			pays->setValue(rec.value("pays"));
			modeReglement->setValue(rec.value("modeReglement"));
			conditionReglement->setValue(rec.value("conditionReglement"));
			user->setValue(CGlobal::getCurrentUser());
			attn->setValue(rec.value("attn"));
			prospect->setValue(rec.value("codeProspect"));
			commentaires->setValue(rec.value("commentaires").toString());
			privateCommentaires->setValue(rec.value("privateCommentaires").toString());
			total->setValue(rec.value("total"));
			titre->setValue(rec.value("titre"));
			stat->setValue(rec.value("stat"));
		}
	}
	delete query;
}
//------------------------------------------------------------------------------
void CDevisFrm::loadLigneFromOther(int Other) {
	QString requete="INSERT INTO ligneDevis ";
	requete+="(devis, numeroLigne, article, descriptionArticle, quantite, prixUnitaireHT, unite, tauxTva, nomTva) ";
	requete+="SELECT "+curCode+", ld.numeroLigne, ld.article, ld.descriptionArticle, ld.quantite, ld.prixUnitaireHT, ";
	requete+="ld.unite, IF(tc.id IS NULL, tp.taux, tc.taux), IF(tc.id IS NULL, tp.nom, tc.nom) ";
	requete+="FROM ligneDevis AS ld ";
	requete+="INNER JOIN teteDevis AS td ON td.code="+curCode+" ";
	requete+="INNER JOIN article AS a ON a.code=ld.article ";
	requete+="LEFT JOIN tvaClient AS tc ON tc.codeClient = td.codeClient AND tc.idTva=a.idTva  ";
	requete+="LEFT JOIN tvaProspect AS tp ON tp.codeProspect=td.codeProspect AND tp.idTva=a.idTva  ";
	requete+="WHERE ld.devis = "+QString::number(Other);
	
	if(CMySQL::getInstance()->execQuery(requete) == 0) {
		return;
	}
	
	loadGrille();
}
//------------------------------------------------------------------------------
void CDevisFrm::swapRows(int n1, int n2)
{
	QString requete="UPDATE ligneDevis SET numeroLigne=-"+QString().number(n1)+" WHERE devis="+curCode+" AND numeroLigne="+QString().number(n1);
	CMySQL::getInstance()->execQuery(requete);
	requete="UPDATE ligneDevis SET numeroLigne="+QString().number(n1)+" WHERE devis="+curCode+" AND numeroLigne="+QString().number(n2);
	CMySQL::getInstance()->execQuery(requete);
	requete="UPDATE ligneDevis SET numeroLigne="+QString().number(n2)+" WHERE devis="+curCode+" AND numeroLigne=-"+QString().number(n1);
	CMySQL::getInstance()->execQuery(requete);
}
//------------------------------------------------------------------------------
void CDevisFrm::showFormulaire(QSqlQuery *query, CGlobal::EAction& action)
{
	QSqlRecord rec=query->record();
	
	curCode=rec.value("code").toString();
	
	code->setValue(curCode);
	codeClient->setValue(rec.value("codeClient"));
	nomDevis->setValue(rec.value("nomDevis"));
	nomClient->setValue(rec.value("nomClient"));
	nomClient2->setValue(!actLock->isChecked() ? rec.value("nomClient") : "");
	adresse1->setValue(rec.value("adresse1"));
	adresse2->setValue(rec.value("adresse2"));
	adresse3->setValue(rec.value("adresse3"));
	codePostal->setValue(rec.value("codePostal"));
	ville->setValue(rec.value("ville"));
	pays->setValue(rec.value("pays"));
	modeReglement->setValue(rec.value("modeReglement"));
	conditionReglement->setValue(rec.value("conditionReglement"));
	creation->setValue(rec.value("creation"));
	user->setValue(rec.value("user"));
	attn->setValue(rec.value("attn"));
	status->setCurrentIndex(status->findText(rec.value("status").toString()));
	prospect->setValue(rec.value("codeProspect"));
	commentaires->setValue(rec.value("commentaires").toString());
	privateCommentaires->setValue(rec.value("privateCommentaires").toString());
	total->setValue(rec.value("total"));
	titre->setValue(rec.value("titre"));
	stat->setValue(rec.value("stat"));
	
	tabWidget->setTabIcon(odiCmtrs, commentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
	tabWidget->setTabIcon(odiPCmtrs, privateCommentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
	
	loadGrille();
}
//------------------------------------------------------------------------------
void CDevisFrm::showChampsAuto(void) {
	QString requete="SELECT nomDevis FROM "+masterTable+" WHERE "+primaryKey+" = "+curCode;
	QSqlQuery *query;

	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		if(query->next()) {
			QSqlRecord rec=query->record();
			
			nomDevis->setValue(rec.value("nomDevis"));
		}
	}
	
	delete query;
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actAjouter_triggered(void)
{	
	setActionCur(CGlobal::acAjout);
	
	creation->setValue(CMySQL::getInstance()->getCurrentDate());
	user->setValue(CGlobal::getCurrentUser());
	montant->setText("0.00");
	TTC->setText("0.00");
	tabWidget->setTabIcon(odiCmtrs, QIcon());
	tabWidget->setTabIcon(odiPCmtrs, QIcon());
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actValider_triggered(void) {
	QString requete;
	QString condition;
	QString oldCode;
	QVariant lastCode;
	
	calculChamps(getActionCur());
	
	if(!validChamps()) return;
	if(!validLiaison()) return;
	
	switch(getActionCur()) {
		case CGlobal::acAjout:
		case CGlobal::acAjoutFromOther:
			requete="INSERT INTO "+masterTable+" SET creation=CURDATE(), createur=\""+CGlobal::getCurrentUser()+"\", ";
			condition="";
			break;
		case CGlobal::acModif:
			requete="UPDATE "+masterTable+" SET ";
			requete+="modification=CURDATE(), modificateur=\""+CGlobal::getCurrentUser()+"\", ";
			condition="WHERE "+primaryKey+"=\""+code->getValue()+"\"";
			break;
		default:
			return;
	}
	
	requete+="codeClient = "+(codeClient->getValue() == "" ? "NULL" : "\""+codeClient->getValue()+"\"")+", ";
	requete+="nomClient = \""+nomClient->getValue()+"\", ";
	requete+="adresse1 = \""+adresse1->getValue()+"\", adresse2 = \""+adresse2->getValue()+"\", ";
	requete+="adresse3 = \""+adresse3->getValue()+"\", codePostal = \""+codePostal->getValue()+"\", ";
	requete+="ville = \""+ville->getValue()+"\", pays = \""+pays->getValue()+"\", ";
	requete+="modeReglement = \""+modeReglement->getValue()+"\", ";
	requete+="conditionReglement = \""+conditionReglement->getValue()+"\", ";
	requete+="user = \""+user->getValue()+"\", attn = \""+attn->getValue()+"\", ";
	requete+="status = \""+status->currentText()+"\", ";
	requete+="codeProspect = "+(prospect->getValue() == "" ? "NULL" : "\""+prospect->getValue()+"\"")+", ";
	requete+="commentaires = \""+commentaires->getValue()+"\", privateCommentaires = \""+privateCommentaires->getValue()+"\", ";
	requete+="total = \""+total->getValue()+"\", titre = \""+titre->getValue()+"\", stat = \""+stat->getValue()+"\" ";
	requete+=condition;
	
	if(CMySQL::getInstance()->execQuery(requete, true, &lastCode) == 0) {
		return;
	}
	
	switch(getActionCur()) {
		case CGlobal::acAjoutFromOther:
			setActionCur(CGlobal::acNone);
			oldCode=curCode;
			curCode=lastCode.toString();
			loadLigneFromOther(oldCode.toInt());
			code->setValue(curCode);
			showChampsAuto();
			break;
		case CGlobal::acAjout:
			setActionCur(CGlobal::acNone);
			curCode=lastCode.toString();
			code->setValue(curCode);
			showChampsAuto();
			break;
		default:
			setActionCur(CGlobal::acNone);
			curCode=code->getValue();
	}
	
	tabWidget->setTabIcon(odiCmtrs, commentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
	tabWidget->setTabIcon(odiPCmtrs, privateCommentaires->getValue() != ""  ? QIcon(":coMexpert/images/irkickflash.png") : QIcon());
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actAnnuler_triggered(void)
{
	
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir annuler ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes)
	{
		if(!chargeDonnees(curCode, CGlobal::seNone))
		{
			if(!chargeDonnees(curCode, CGlobal::sePrecedent))
			{
				if(!chargeDonnees(curCode, CGlobal::seSuivant))
				{
					setActionCur(CGlobal::acTableVide);
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actSupprimer_triggered(void)
{
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir supprimer la fiche courante ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes)
	{
		QString requete="DELETE FROM "+masterTable+" WHERE "+primaryKey+"=\""+curCode+"\"";
		
		CMySQL::getInstance()->execQuery(requete);
		
		if(!chargeDonnees(curCode, CGlobal::sePrecedent))
		{
			if(!chargeDonnees(curCode, CGlobal::seSuivant))
			{
				setActionCur(CGlobal::acTableVide);
			}
		}
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::onChange(void)
{
	if(getActionCur() == CGlobal::acNone)
	{
		setActionCur(CGlobal::acModif);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::onChangeClientProspect(void)
{
	if(getActionCur() == CGlobal::acNone || getActionCur() == CGlobal::acModif)
	{
		if(!avertModifClientShown) {
			QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
								tr("Etes vous sûre de modifier le client du devis ?"), QMessageBox::Yes | QMessageBox::No);
			
			msgBox.exec();
			
			if(msgBox.result() == QMessageBox::No)
			{
				QSqlQuery *query;
				QString requete="SELECT codeClient, codeProspect FROM teteDevis WHERE code="+curCode;
				
				if(CMySQL::getInstance()->execQuery(requete, &query))
				{
					if(query->next())
					{
						QSqlRecord rec=query->record();
						
						codeClient->setValue(rec.value("codeClient"));
						prospect->setValue(rec.value("codeProspect"));
					}
				}
				
				delete query;
			}else {
				avertModifClientShown=true;
				setActionCur(CGlobal::acModif);
			}
		}else {
			setActionCur(CGlobal::acModif);
		}
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::onCombo(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::onComboClient(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
		
		loadInfoClient(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::onComboProspect(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
		
		loadInfoProspect(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::onComboAttn(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm;
	
	if(prospect->getValue() != "")
	{
		comboResultFrm=new CComboResultFrm("contactProspect", "prospect", this, 1, "prospect=\""+prospect->getValue()+"\"");
	}else
	{
		comboResultFrm=new CComboResultFrm("contactClient", "client", this, 1, "client=\""+codeClient->getValue()+"\"");
	}
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
		onChange();
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::onClientEditingFinished(void)
{
	QString client=codeClient->getValue();
	
	if(client != "")
	{
		loadInfoClient(client);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actRechercheUneFiche_triggered(void)
{
	CFindFrm *findFrm=new CFindFrm(masterTable, this);
	
	findFrm->setModal(true);
	findFrm->exec();
	if(findFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::ajouteLigne(bool &goToLast)
{
	CSelectArticleFrm *selectArticleFrm=new CSelectArticleFrm(this);
	
	if(selectArticleFrm->exec())
	{
		QString requete;
		QString numeroLigne=CMySQL::getInstance()->getNextCode("ligneDevis", "numeroLigne", "devis="+curCode);
		QString article=selectArticleFrm->getArticle();
		
		requete="INSERT INTO ligneDevis (devis, article, descriptionArticle, quantite, prixUnitaireHT, unite, tauxTva, nomTva) ";
		requete+="SELECT "+curCode+", \""+article+"\", a.nom, 1, ";
		requete+="IF(pac.prix IS NOT NULL, pac.prix, a.prixUnitaireHT), a.unite, IF(tc.id IS NULL, tp.taux, tc.taux), ";
		requete+="IF(tc.id IS NULL, tp.nom, tc.nom) ";
		requete+="FROM article AS a ";
		requete+="LEFT JOIN prixArticleClient AS pac ON a.code=pac.article AND pac.client = \""+codeClient->getValue()+"\" ";
		requete+="LEFT JOIN tvaClient AS tc ON tc.codeClient=\""+codeClient->getValue()+"\" AND tc.idTva=a.idTva ";
		requete+="LEFT JOIN tvaProspect AS tp ON tp.codeProspect=\""+prospect->getValue()+"\" AND tp.idTva=a.idTva ";
		requete+="WHERE a.code = \""+article+"\" ";
		requete+="ORDER BY pac.numero DESC LIMIT 1 ";
		
		CMySQL::getInstance()->execQuery(requete);
		
		setActionCur(CGlobal::acNone);
		
		loadGrille();
	}
	
	delete selectArticleFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::supprimeLigne(int row, bool& ok)
{
	QTableWidgetItem *item=lignesWidget->item(lignesWidget->currentRow(), 0);
	int numeroLigne;
	
	if(item != NULL)
	{
		numeroLigne=item->text().toInt();
		
		QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
							tr("Etes vous sûre de vouloir supprimer la ligne numero ")+
							QString().number(numeroLigne)+tr(" ?"), QMessageBox::Yes | QMessageBox::No);
		msgBox.exec();
		
		if(msgBox.result() == QMessageBox::Yes)
		{
			QString requete;
			
			requete="DELETE from ligneDevis WHERE devis = "+curCode+" AND numeroLigne = "+QString().number(numeroLigne);
			
			CMySQL::getInstance()->execQuery(requete);
			
			ok=true;
		}
		
		calculMontant(row);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::monteLigne(int row)
{
	if(row > 0)
	{
		bool tableSwap[]={false, true, true, true, true, true, true};
		
		lignesWidget->swapRows(row, row-1, tableSwap);
		
		int curLigne=lignesWidget->item(row, cndLigne)->text().toInt();
		int ligneSwap=lignesWidget->item(row-1, cndLigne)->text().toInt();
		
		swapRows(curLigne, ligneSwap);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::descendLigne(int row)
{
	if(row >=0 && row < lignesWidget->rowCount()-1)
	{
		bool tableSwap[]={false, true, true, true, true, true, true};
		
		lignesWidget->swapRows(row, row+1, tableSwap);
		
		int curLigne=lignesWidget->item(row, cndLigne)->text().toInt();
		int ligneSwap=lignesWidget->item(row+1, cndLigne)->text().toInt();
		
		swapRows(curLigne, ligneSwap);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::modifiLigne(int row, int column)
{
	QString requete;
	QTableWidgetItem *item;
	
	if(getActionCur() != CGlobal::acNone) return;
	item=lignesWidget->item(row, column);
	
	if(column != cndLigne && column != cndTotal && column != cndTva)
	{
		QString text=lignesWidget->getColumnModel(column)->format(item->text());
		QString textSQL=lignesWidget->getColumnModel(column)->formatToSQL(CGlobal::addSlashesQuot(item->text()));
		
		requete="UPDATE ligneDevis ";
		requete+="SET "+lignesWidget->getColumnModel(column)->getNomChamp()+" = "+textSQL+" ";
		requete+="WHERE devis="+curCode+" AND numeroLigne="+lignesWidget->item(row, 0)->text();
		
		item->setText(text);
		
		CMySQL::getInstance()->execQuery(requete);
		
		calculTotalLigne(row);
		calculMontant();
		
		lignesWidget->resizeRowToContents(row);
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::ligneDoubleClicked(int row, int column)
{
	CComboResultFrm *comboResultFrm;
	
	switch(column)
	{
		case cndArticle:
			comboResultFrm=new CComboResultFrm("article", "code", this);
		
			comboResultFrm->setModal(true);
			comboResultFrm->exec();
		
			if(comboResultFrm->result() == QDialog::Accepted)
			{
				QString requete;
				QTableWidgetItem *item=lignesWidget->item(row, column);
				QString ligne=lignesWidget->item(row, cndLigne)->text();
				QString article=item->text();
				
				article=comboResultFrm->getResult();
				item->setText(article);
				
				requete="UPDATE ligneDevis AS ld ";
				requete+="INNER JOIN article AS a ON a.code=ld.article ";
				requete+="LEFT JOIN prixArticleClient AS pac ON pac.article=ld.article AND pac.client=\""+codeClient->getValue()+"\" ";
				requete+="SET ld.article=\""+article+"\", ld.descriptionArticle=a.nom, ";
				requete+="ld.prixUnitaireHT=IF(pac.prix IS NOT NULL, pac.prix, a.prixUnitaireHT), ld.unite=a.unite ";
				requete+="WHERE a.code=\""+article+"\" AND ld.numeroLigne="+ligne+" AND ld.devis="+curCode;
				
				if(CMySQL::getInstance()->execQuery(requete))
				{
					loadGrille();
				}
			}
		
			delete comboResultFrm;
			break;
		case cndUnite:
			comboResultFrm=new CComboResultFrm("unites", "code", this);
		
			comboResultFrm->setModal(true);
			comboResultFrm->exec();
		
			if(comboResultFrm->result() == QDialog::Accepted)
			{
				QTableWidgetItem *item;
		
				item=lignesWidget->item(row, column);
				
				item->setText(comboResultFrm->getResult());
			}
		
			delete comboResultFrm;
			break;
		default:
			break;
	}
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actCopierDevis_triggered(void)
{
	setActionCur(CGlobal::acAjoutFromOther);
	
	creation->setValue(CMySQL::getInstance()->getCurrentDate());
	user->setValue(CGlobal::getCurrentUser());
	montant->setText("0.00");
	TTC->setText("0.00");
	
	loadEnteteFromOther();
	status->setCurrentIndex(0);
}
//------------------------------------------------------------------------------
void CDevisFrm::on_cmdAdresse_clicked(bool checked)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm("adressesClient", "nom", this, 0, "client = \""+codeClient->getValue()+"\"");
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		loadInfoAdresse(comboResultFrm->getResult().toInt());
		onChange();
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CDevisFrm::onInvokeHelp(CChamp *champ)
{
	CHelp::getInstance()->startHelp("setSource qthelp://alpes-ressources.com.coMexpert-"+VERSION_LOGICIEL+"/doc/devis.html#"+champ->getTable()+"."+champ->getChamp());
}
//------------------------------------------------------------------------------
void CDevisFrm::on_actLock_triggered(void) {
	eWidget->setVisible(actLock->isChecked());
	nomClient2->setValue(!actLock->isChecked() ? nomClient->getValue() : "");
}
//------------------------------------------------------------------------------

